﻿using DotNetOpenAuth.OAuth2;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Constants;
namespace TestWebForOauth2._0.Controllers
{
    public class HomeController : Controller
    {
        private WebServerClient webclient = null;
        private static string _accessToken;
        public ActionResult Index()
        {
            InitWebServerClient();//初始化webclient
            var  accessToken = Request.Form["AccessToken"] ?? "";//获取accessToken
            
            if(string.IsNullOrWhiteSpace(accessToken))//没有获取到授权码，请求授权
            {
                RequestToken();
            }
            return View(accessToken);
        }

        public void InitWebServerClient()
        {
            var authorizationServerUrl = new Uri(Paths.AuthorizationServerBaseAddress);
            var authorizationServer = new AuthorizationServerDescription {
                AuthorizationEndpoint=new Uri(authorizationServerUrl,Paths.AuthorizePath),
                TokenEndpoint=new Uri(authorizationServerUrl,Paths.TokenPath)
            };
            webclient = new WebServerClient(authorizationServer, Clients.Client1.Id, Clients.Client1.Secret);
        }

        public void RequestToken()
        {
            var state = webclient.GetClientAccessToken(new[] { "bio", "notes" });
            _accessToken = state.AccessToken;
            
        }
        public ActionResult About()
        {
            ViewBag.Message = "Your application description page.";

            return View();
        }

        public ActionResult Contact()
        {
            ViewBag.Message = "Your contact page.";

            return View();
        }
    }
}